<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Pegawai extends CI_Controller {

    function __construct() 
	{
        parent::__construct();
        $this->load->library('flexigrid');
        $this->load->library('form_validation');
        $this->load->helper('flexigrid');
        $this->load->helper(array('form', 'url'));
        $this->load->model('pegawai_model');
		// $this->load->model('periode_model');
    }

    //load Grid
    function index() 
	{
        if ($this->session->userdata('username') == NULL) 
		{
            redirect('login');
        } else {
            $colModel['no'] = array('No', 30, TRUE, 'center', 0);
            $colModel['NAMA_PEGAWAI'] = array('Nama Pegawai', 250, TRUE, 'center', 1);
            $colModel['DEPARTEMEN_PEGAWAI'] = array('Departemen Pegawai', 170, TRUE, 'center', 1);
            $colModel['STATUS'] = array('Status', 50, TRUE, 'center', 1);
            $colModel['Edit'] = array('Edit', 30, TRUE, 'center', 0);
			$colModel['Detail_Pegawai'] = array('Detail Pegawai', 70, TRUE, 'center', 0);

            $gridParams = array(
                'width' => 'auto',
                'height' => 300,
                'rp' => 10,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
                'title' => 'Daftar Pegawai',
                'showTableToggleBtn' => true
            );

            $buttons[] = array('tambah', 'add', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('hapus', 'delete', 'spt_js');


            // mengambil data dari file controler ajax pada method grid_foto
            $grid_js = build_grid_js('flex1', site_url("pegawai/grid_foto"), $colModel, 'NAMA_PEGAWAI', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
        function spt_js(com,grid)
        {
                if (com=='tambah')
                {
                        location.href='" . base_url() . "index.php/pegawai/form';
                }

                if (com=='hapus')
                        {
                           if($('.trSelected',grid).length>0){
                                   if(confirm('Anda yakin menghapus ' + $('.trSelected',grid).length + ' pegawai?')){
                                                var items = $('.trSelected',grid);
                                                var itemlist ='';
                                                for(i=0;i<items.length;i++){
                                                        itemlist+= items[i].id.substr(3)+',';
                                                }
                                                $.ajax({
                                                   type: 'POST',
                                                   url: '" . base_url() . "index.php/pegawai/delete" . "',
                                                   data: 'items='+itemlist,
                                                   success: function(data){
                                                        $('#flex1').flexReload();
														alert(data);
                                                   }
                                                });
                                        }
                                } else {
                                        return false;
                                }
                        }

        }
        </script>
        ";


            $data['js_grid'] = $grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid_foto() 
	{
        $valid_fields = array('NAMA_PEGAWAI', 'DEPARTEMEN_PEGAWAI', 'STATUS');
        $this->flexigrid->validate_post('NAMA_PEGAWAI', 'asc', $valid_fields);
		$records = $this->pegawai_model->get_data_pegawai();
		$this->output->set_header($this->config->item('json_header'));
        $no = 0;
		
        foreach ($records['records']->result() as $row) {
            $status_aktif = "";
            // $lokasi_foto = base_url() . $row->foto_santri;
            $new_tab = 'target="_blank"';
			$nama_pegawai = str_replace("\'", "'", $row->NAMA_PEGAWAI);
            $record_items[] = array(
                $row->ID_PEGAWAI,
                $no = $no + 1,
                //'<a href= \'' . $lokasi_foto . '\' ' . $new_tab . '><img border=\'0\' src=\'' . $lokasi_foto . '\' height=\'50\'></a> ',
                $nama_pegawai,
                $row->DEPARTEMEN_PEGAWAI,
                $row->STATUS,
                '<a href=\'' . base_url() . 'index.php/pegawai/edit/' . $row->ID_PEGAWAI . '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/edit.png\'></a> ',
				'<a href=\'' . base_url() . 'index.php/pegawai/detail_pegawai/' . $row->ID_PEGAWAI. '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/page.png\'></a> ',	
            );
			
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }

    function form() 
	{
        if ($this->session->userdata('username') == NULL) 
		{
            redirect('login');
        } else {
            $data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
            $data['content'] = $this->load->view('form_pegawai', $data, true);
            $this->load->view('main', $data);
        }
    }

    function upload() 
	{
        if ($this->session->userdata('username') == NULL) 
		{
            redirect('login');
        } else {
            if ($this->cek_validasi() == FALSE) 
			{
                $this->form();
            } else {
                $field_name = 'FOTO_PEGAWAI';
                $config['upload_path'] = "gallery/pegawai";
                $config['allowed_types'] = '*';
                //$config['allowed_types'] ='jpg';
				
				//create folder
				if(!is_dir($config['upload_path']))
				{
					mkdir($config['upload_path'], 0777);
				}

                $this->load->library('upload', $config);
                $files = $this->upload->do_upload($field_name);

                $data = $this->upload->data($field_name); //get file_name
                    
				if (!$files) 
				{
					$file_name = 'default.jpg';
				}
				else {
					$file_name = $data['file_name'];
				}
					
                $path[0] = 'gallery/pegawai/' . $file_name;
                $path[1] = $file_name;
                //return $path;
				
                $data = array(						
						'NAMA_PEGAWAI' => $this->input->post('NAMA_PEGAWAI'),
						'NAMA_PANGGILAN' => $this->input->post('NAMA_PANGGILAN'),
						'TEMPAT_LAHIR' => $this->input->post('TEMPAT_LAHIR'),
						'TANGGAL_LAHIR' => $this->input->post('TANGGAL_LAHIR'),
						'GOLONGAN_DARAH' => $this->input->post('GOLONGAN_DARAH'),
						'AGAMA' => $this->input->post('AGAMA'),
						'SUKU' => $this->input->post('SUKU'),
						'BAHASA_SEHARI' => $this->input->post('BAHASA_SEHARI'),
						'DEPARTEMEN_PEGAWAI' => $this->input->post('DEPARTEMEN_PEGAWAI'),
						'BENGKEL' => $this->input->post('BENGKEL'),
						'ALAMAT' => $this->input->post('ALAMAT'),
						'TELEPON' => $this->input->post('TELEPON'),
						'STATUS' => $this->input->post('STATUS'),
						'FOTO_PEGAWAI' => $path[0]					
                );
				
				$data = str_replace("'", "\'", $data);
				$this->pegawai_model->insert($data);
				redirect('pegawai');
            }
        }
    }
    

    public function edit($id) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $data['status'] = 'edit';
            $record_artikel = $this->pegawai_model->selectone($id);
            foreach ($record_artikel->result() as $artikel) 
			{
				$data['ID_PEGAWAI'] = $artikel->ID_PEGAWAI;
                $data['NAMA_PEGAWAI'] = $artikel->NAMA_PEGAWAI;
                $data['NAMA_PANGGILAN'] = $artikel->NAMA_PANGGILAN;
                $data['TEMPAT_LAHIR'] = $artikel->TEMPAT_LAHIR;
                $data['TANGGAL_LAHIR'] = $artikel->TANGGAL_LAHIR;
                $data['GOLONGAN_DARAH'] = $artikel->GOLONGAN_DARAH;
                $data['AGAMA'] = $artikel->AGAMA;
                $data['SUKU'] = $artikel->SUKU;
                $data['BAHASA_SEHARI'] = $artikel->BAHASA_SEHARI;
                $data['DEPARTEMEN_PEGAWAI'] = $artikel->DEPARTEMEN_PEGAWAI;
                $data['BENGKEL'] = $artikel->BENGKEL;
                $data['ALAMAT'] = $artikel->ALAMAT;
                $data['TELEPON'] = $artikel->TELEPON;
                $data['STATUS'] = $artikel->STATUS;
				$data['FOTO_PEGAWAI'] = base_url() . $artikel->FOTO_PEGAWAI;								
            }
            $data['failed'] = false;
            $data['aa'] = '';
			$data = str_replace("\'", "'", $data);
            $data['pegawai'] = $this->pegawai_model->get_data_all_pegawai();
			$data['content'] = $this->load->view('form_pegawai', $data, true);
            $this->load->view('main', $data);
        }
    }

    function update($id) 
	{
        if ($this->session->userdata('username') == NULL) 
		{
            redirect('login');
        } else {
            if ($this->cek_validasi() == FALSE) 
			{
                $this->edit($id);
            } else {
                $field_name = 'FOTO_PEGAWAI';
                $config['upload_path'] = "gallery/pegawai";
                $config['allowed_types'] = '*';
				
				//create folder
				if(!is_dir($config['upload_path']))
				{
					mkdir($config['upload_path'], 0777);
				}
                
                $this->load->library('upload', $config);
                $files = $this->upload->do_upload($field_name);
                $file_name = '';

                if (!$files) 
				{
                    $data = $this->upload->data($field_name); //get file_name
                    $file_name = $data['file_name'];
                    $path[0] = 'gallery/pegawai/' . $file_name;
                    $path[1] = $file_name;				
														
					$data = array(
						'NAMA_PEGAWAI' => $this->input->post('NAMA_PEGAWAI'), 
                        'NAMA_PANGGILAN' => $this->input->post('NAMA_PANGGILAN'),
                        'TEMPAT_LAHIR' => $this->input->post('TEMPAT_LAHIR'),
                        'TANGGAL_LAHIR' => $this->input->post('TANGGAL_LAHIR'),
                        'GOLONGAN_DARAH' => $this->input->post('GOLONGAN_DARAH'),
                        'AGAMA' => $this->input->post('AGAMA'),
                        'SUKU' => $this->input->post('SUKU'),
                        'BAHASA_SEHARI' => $this->input->post('BAHASA_SEHARI'),      
                        'DEPARTEMEN_PEGAWAI' => $this->input->post('DEPARTEMEN_PEGAWAI'),
                        'BENGKEL' => $this->input->post('BENGKEL'),
                        'ALAMAT' => $this->input->post('ALAMAT'),
                        'TELEPON' => $this->input->post('TELEPON'),
                        'STATUS' => $this->input->post('STATUS')											
						);
					$data = str_replace("'", "\'", $data);
                    $this->pegawai_model->update($id, $data);
                    redirect('pegawai');
                } else {
                    $data = $this->upload->data($field_name); //get file_name
                    $file_name = $data['file_name'];
                    $path[0] = 'gallery/pegawai/' . $file_name;
                    $path[1] = $file_name;
                    
                    $data = array(
						'NAMA_PEGAWAI' => $this->input->post('NAMA_PEGAWAI'), 
                        'NAMA_PANGGILAN' => $this->input->post('NAMA_PANGGILAN'),
                        'TEMPAT_LAHIR' => $this->input->post('TEMPAT_LAHIR'),
                        'TANGGAL_LAHIR' => $this->input->post('TANGGAL_LAHIR'),
                        'GOLONGAN_DARAH' => $this->input->post('GOLONGAN_DARAH'),
                        'AGAMA' => $this->input->post('AGAMA'),
                        'SUKU' => $this->input->post('SUKU'),
                        'BAHASA_SEHARI' => $this->input->post('BAHASA_SEHARI'),      
                        'DEPARTEMEN_PEGAWAI' => $this->input->post('DEPARTEMEN_PEGAWAI'),
                        'BENGKEL' => $this->input->post('BENGKEL'),
                        'ALAMAT' => $this->input->post('ALAMAT'),
                        'TELEPON' => $this->input->post('TELEPON'),
                        'STATUS' => $this->input->post('STATUS'),
                        'FOTO_PEGAWAI' => $path[0]
                    );
					$data = str_replace("'", "\'", $data);
                    $this->pegawai_model->update($id, $data);
                    redirect('pegawai');
                }
            }
        }
    }
	
	function detail_pegawai($id) 
	{
        if ($this->session->userdata('username') == NULL) 
		{
            redirect('login');
        } else {
            $data['status'] = 'detail_pegawai';
            $record_artikel = $this->pegawai_model->selectone($id);
            foreach ($record_artikel->result() as $artikel) 
			{
				$data['ID_PEGAWAI'] = $artikel->ID_PEGAWAI;
                $data['NAMA_PEGAWAI'] = $artikel->NAMA_PEGAWAI;
                $data['NAMA_PANGGILAN'] = $artikel->NAMA_PANGGILAN;
                $data['TEMPAT_LAHIR'] = $artikel->TEMPAT_LAHIR;
                $data['TANGGAL_LAHIR'] = $artikel->TANGGAL_LAHIR;
                $data['GOLONGAN_DARAH'] = $artikel->GOLONGAN_DARAH;
                $data['AGAMA'] = $artikel->AGAMA;
                $data['SUKU'] = $artikel->SUKU;
                $data['BAHASA_SEHARI'] = $artikel->BAHASA_SEHARI;
                $data['DEPARTEMEN_PEGAWAI'] = $artikel->DEPARTEMEN_PEGAWAI;
                $data['BENGKEL'] = $artikel->BENGKEL;
                $data['ALAMAT'] = $artikel->ALAMAT;
                $data['TELEPON'] = $artikel->TELEPON;
                $data['STATUS'] = $artikel->STATUS;
				$data['FOTO_PEGAWAI'] = base_url() . $artikel->FOTO_PEGAWAI;				
            }
            $data['failed'] = false;
            $data['aa'] = '';
			$data = str_replace("\'", "'", $data);
            $data['pegawai'] = $this->pegawai_model->get_data_all_pegawai();
			$data['content'] = $this->load->view('detail_pegawai', $data, true);
            $this->load->view('main', $data);
        }
    }

    function delete() 
	{
        if ($this->session->userdata('username') == NULL) 
		{
            redirect('login');
        } else {
			$spt_ids_post_array = explode(",", $this->input->post('items'));
            foreach ($spt_ids_post_array as $id_pegawai)
			{
				//cek data ustad
				if (isset($id_pegawai) && $id_pegawai != '') {
					$sql = $this->db->query("SELECT SUM(NAMA_PEGAWAI) AS CEK FROM pegawai WHERE ID_PEGAWAI = ".$id_pegawai."");
					$cek = '';
					foreach ($sql->result() as $rows)
					{
						$cek = $rows->CEK;
					}
							
					$msg='';
					if($cek > 0)
					{
						$msg ='Proses hapus gagal. Pegawai masih aktif.';
					} else {
						$this->pegawai_model->delete($id_pegawai);
						$msg ='Data yang Anda pilih berhasil dihapus.';
					}
					$this->output->set_header($this->config->item('ajax_header'));
					$this->output->set_output($msg);
				}
			}
        }
    }
	
	function alpha_space($str)
    {
        return ( ! preg_match("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ", $str)) ? FALSE : TRUE;
    } 

    function cek_validasi() 
	{
        // Setting Rules
        $this->form_validation->set_rules('NAMA_PEGAWAI', 'Nama Pegawai', 'required');
		$this->form_validation->set_rules('NAMA_PANGGILAN', 'Nama Panggilan', 'required');
		$this->form_validation->set_rules('TEMPAT_LAHIR', 'Tempat lahir', 'required');
		$this->form_validation->set_rules('TANGGAL_LAHIR', 'Tanggal lahir', 'required');
		$this->form_validation->set_rules('GOLONGAN_DARAH', 'Golongan Darah', 'required');
		$this->form_validation->set_rules('AGAMA', 'Agama', 'required');
		$this->form_validation->set_rules('SUKU', 'Suku', 'required');
		$this->form_validation->set_rules('BAHASA_SEHARI', 'Bahasa sehari', 'required');
		$this->form_validation->set_rules('DEPARTEMEN_PEGAWAI', 'Departemen Pegawai', 'required');
		$this->form_validation->set_rules('ALAMAT', 'Alamat', 'required');
		$this->form_validation->set_rules('TELEPON', 'Telepon', 'numeric');
		$this->form_validation->set_rules('STATUS', 'Status Pegawai', 'required');
		
		
        //Setting Error Message
        $this->form_validation->set_message('required', 'Field %s harus diisi.');
        $this->form_validation->set_message('numeric', 'Field %s harus diisi angka.');
		$this->form_validation->set_message('greater_than', 'Field %s harus diisi angka lebih dari 0');
		//$this->form_validation->set_message('alpha_space', 'Field %s harus diisi dengan huruf dan spasi');

        // Setting Delimiter
        $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }
	
}
